<?php

namespace App\Http\Controllers\ModelManage;

use App\Http\Controllers\Controller;
use App\Http\Requests\ModelManage\TableFieldRequest;
use App\Models\ModelManage\Database;
use App\Models\ModelManage\JsonField;
use App\Models\ModelManage\Table;
use App\Models\ModelManage\TableField;
use App\Repositories\ModelManage\TableFieldRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;

class TableFieldController extends Controller
{
    use ModelForm;

    /** @var  TableFieldRepository */
    private $tableFieldRepository;

    public function __construct(TableFieldRepository $tableFieldRepo)
    {
        $this->tableFieldRepository = $tableFieldRepo;
    }

    /**
     * Display a listing of the TableField.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('model_manage.table_fields.index_header'));
            $content->description(__('model_manage.table_fields.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new TableField.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('model_manage.table_fields.create_header'));
            $content->description(__('model_manage.table_fields.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created TableField in storage.
     *
     * @param TableFieldRequest $request
     *
     * @return Response
     */
    public function store(TableFieldRequest $request)
    {
        $input              = $request->all();
        $tableFieldCount    = TableField::count();
        $input['listorder'] = $tableFieldCount + 1;
        $tableField         = $this->tableFieldRepository->create($input);

        Flash::success(__('model_manage.table_fields.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('model_manage.table_fields.index'));

    }

    /**
     * Display the specified TableField.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $tableField = $this->tableFieldRepository->findWithoutFail($id);

        if (empty($tableField)) {
            Flash::error(__('model_manage.table_fields.not_found'));

            return redirect(route('model_manage.table_fields.index'));
        }

        return view('model_manage.table_fields.show')->with('tableField', $tableField);

    }

    /**
     * Show the form for editing the specified TableField.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('model_manage.table_fields.edit_header'));
            $content->description(__('model_manage.table_fields.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified TableField in storage.
     *
     * @param  int              $id
     * @param TableFieldRequest $request
     *
     * @return Response
     */
    public function update($id, TableFieldRequest $request)
    {
        $tableField = $this->tableFieldRepository->findWithoutFail($id);

        if (empty($tableField)) {
            Flash::error(__('model_manage.table_fields.not_found'));

            return redirect(route('model_manage.table_fields.index'));
        }
        $input = $request->all();

        $tableField = $this->tableFieldRepository->update($input, $id);

        Flash::success(__('model_manage.table_fields.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('model_manage.table_fields.index'));
    }

    /**
     * Remove the specified TableField from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->tableFieldRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('model_manage.table_fields.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $tableField = $this->tableFieldRepository->findWithoutFail($id);

        if (empty($tableField)) {
            Flash::error(__('model_manage.table_fields.not_found'));

            return redirect(route('model_manage.table_fields.index'));
        }

        if ($flag = $this->tableFieldRepository->delete($id)) {

            return response()->json(['message' => __('model_manage.table_fields.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(TableField::class, function (Form $form) {

            $form->display('id', 'ID');
            $databases = Database::pluck('title', 'id');
            $form->select('database_id', '所属库')->options($databases);
            $form->text('name', '字段名');
            $form->text('title', '字段别名');
            $fieldType = [
                'integer'  => 'integer',
                'string'   => 'string',
                'text'     => 'text',
                'date'     => 'date',
                'dateTime' => 'dateTime',
                'char'     => 'char',
                'year'     => 'year',
                'boolean'  => 'boolean',
                'float'    => 'float',
                'array'    => 'array',
            ];
            $tables = Table::pluck('title', 'id');
            $form->select('table_id', '表名')->options($tables);
            $form->select('field_type', '字段属性')->options($fieldType);
            $form->switch('field_filter', '视图过滤');
            $form->text('column_width', '视图(宽度)');
            $rw = [
                'r'  => '只读',
                'w'  => '只写',
                'rw' => '读写',
            ];
            $form->radio('rw', '读写')->options($rw)->default('rw');
            $formInput = [
                'text'     => '文本框',
                'select'   => '下拉框',
                'radio'    => '单选框',
                'checkbox' => '复选框',
                'password' => '密码输入框',
                'number'   => '数字输入框',
                'textarea' => 'textarea输入框',
                'editor'   => '富文本编辑框',
                'image'    => '图片框',
                'url'      => 'url输入框',
                'date'     => '日期输入框',
                'datetime' => '日期时间输入框',
                'mobile'   => '电话号码输入框',
                'ip'       => 'ip输入框',
                'email'    => 'email个数输入框',
                'currency' => '货币输入框',
                'rate'     => '比例输入框',
                'color'    => '颜色选择框',
            ];
            $form->select('form', '表单输入')->options($formInput);
            $indexs = [
                '0' => '否',
                '1' => '普通索引',
                '2' => '唯一索引',
            ];
            $form->radio('index', '索引')->options($indexs)->default(0);
            $fieldType = [
                'foreign' => 'foreign',
                'options' => 'options',
                'basic'   => 'basic',
                'maps'    => 'maps',
                'href'    => 'href',
                'flow'    => 'flow',
                'uuid'    => 'uuid',
            ];
            $form->select('type', '类型')->options($fieldType);

            $form->textarea('attr', 'JSON编辑');
            $form->textarea('clone', '克隆');
            $form->textarea('publish', '发布');
            $form->textarea('description', '说明');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(TableField::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('model_manage.table_fields.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('model_manage.table_fields.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('model_manage.table_fields.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('model_manage.table_fields.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('model_manage.table_fields.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('model_manage.table_fields.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('model_manage.table_fields.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('model_manage.table_fields.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('model_manage.table_fields.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('model_manage.table_fields.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('database.title', '库')->sortable();
            $grid->column('name', '字段名')->sortable();
            $grid->column('title', '字段别名')->sortable();
            $grid->column('table.title', '表名')->sortable();
            $grid->column('field_type', '字段属性');
            $grid->column('field_filter', '视图过滤')->sortable()->display(function ($val) {
                switch ($val) {
                    case 'on':
                        return '<span class="badge bg-green">ON</span>';
                        break;
                    case 'off':
                        return '<span class="badge bg-dange">OFF</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('column_width', '视图(宽度)')->sortable();
            $grid->column('rw', '读写')->display(function ($val) {
                switch ($val) {
                    case 'r':
                        return '<span class="badge bg-green">只读</span>';
                        break;
                    case 'w':
                        return '<span class="badge bg-green">只写</span>';
                        break;
                    case 'rw':
                        return '<span class="badge bg-green">读写</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('form', '表单输入')->display(function ($val) {
                switch ($val) {
                    case 'text':
                        return '<span class="badge bg-green">文本框</span>';
                        break;
                    case 'select':
                        return '<span class="badge bg-green">下拉框</span>';
                        break;
                    case 'radio':
                        return '<span class="badge bg-green">单选框</span>';
                        break;
                    case 'checkbox':
                        return '<span class="badge bg-green">复选框</span>';
                        break;
                    case 'password':
                        return '<span class="badge bg-green">密码输入框</span>';
                        break;
                    case 'textarea':
                        return '<span class="badge bg-green">textarea输入框</span>';
                        break;
                    case 'editor':
                        return '<span class="badge bg-green">富文本编辑框</span>';
                        break;
                    case 'image':
                        return '<span class="badge bg-green">图片框</span>';
                        break;
                    case 'url':
                        return '<span class="badge bg-green">url输入框</span>';
                        break;
                    case 'date':
                        return '<span class="badge bg-green">日期输入框</span>';
                        break;
                    case 'datetime':
                        return '<span class="badge bg-green">日期时间输入框</span>';
                        break;
                    case 'mobile':
                        return '<span class="badge bg-green">电话号码输入框</span>';
                        break;
                    case 'ip':
                        return '<span class="badge bg-green">ip输入框</span>';
                        break;
                    case 'email':
                        return '<span class="badge bg-green">email个数输入框</span>';
                        break;
                    case 'currency':
                        return '<span class="badge bg-green">货币输入框</span>';
                        break;
                    case 'rate':
                        return '<span class="badge bg-green">比例输入框</span>';
                        break;
                    case 'color':
                        return '<span class="badge bg-green">颜色选择框</span>';
                        break;
                    case 'editor':
                        return '<span class="badge bg-green">富文本编辑框</span>';
                        break;
                    case 'number':
                        return '<span class="badge bg-green">数字输入框</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('index', '索引')->display(function ($val) {
                switch ($val) {
                    case '0':
                        return '<span class="badge bg-dange">否</span>';
                        break;
                    case '1':
                        return '<span class="badge bg-green">是</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('type', '类型')->sortable();
            $grid->column('attr', 'JSON编辑')->display(function ($val) {
                // 根据当前表,字段,类型daojson_fields获取schema
                $tableId = $this->table_id;
                $fieldId = $this->id;
                // $type    = $this->type;
                // $schema    = JsonField::where(['table_id' => $tableId, 'table_field_id' => $fieldId])->value('schema');
                // $tableName = Table::where(['id' => $this->table_id])->value('name');
                // $fieldName = $this->name;
                // 'table_name' => 'tableName', 'field_name' => $fieldName,
                // 'schema' => $schema,
                return "<a href=" . route('model_manage.table_fields.json_schema.view', ['table_field_id' => $fieldId]) . ">json编辑</a>";
            });
            $grid->column('clone', '克隆')->sortable();
            $grid->column('publish', '发布')->sortable();
            $grid->column('description', '说明')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');
                // 表格
                $tmpTables = Table::pluck('title', 'id');
                $filter->equal('table_id', '表')->select($tmpTables);
            });
        });
    }

    /**
     * 获取表名字段名
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getSchemaView(Request $request)
    {
        $id         = $request->input('table_field_id');
        $tableField = TableField::with(['table'])->where(['id' => $id])->first();
        if (empty($tableField)) {
            Flash::error(__('model_manage.table_fields.not_found'));
            return redirect(route('model_manage.table_fields.index'));
        }
        $tableName              = Table::where(['id' => $tableField->table_id])->value('name');
        $data                   = [];
        $data['table_name']     = $tableName;
        $data['field_name']     = $tableField->name;
        $data['table_field_id'] = $tableField->id;
        // dd($tableField->id,$tableField->table_id);
        $schema         = JsonField::where(['table_id' => $tableField->table_id, 'table_field_id' => $tableField->id])->value('schema');
        $data['schema'] = json_decode($schema);
        $data['data']   = json_decode($tableField->attr);
        // dd($data);
        return view('welcome', ['data' => $data]);
    }

    /**
     * 保存json schema编辑的数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function storeTableFieldAttr(Request $request)
    {
        $data         = $request->input('data');
        $tableFieldId = $request->input('table_field_id');
        $tableField   = TableField::where(['id' => $tableFieldId])->first();
        if (empty($tableField)) {
            return response()->json(['status' => '200', 'data' => '表字段不合法!']);
        }

        $result = DB::table('table_fields')
            ->where(['id' => $tableField])
            ->update(['attr' => $data]);
        if ($result) {
            return response()->json(['status' => '200', 'data' => '保存成功!']);
        } else {
            return response()->json(['status' => '404', 'data' => '保存失败']);
        }
    }
}
